<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <h2>个人中心</h2>
        </div>
      </template>
      
      <div class="profile-content">
        <div class="avatar-section">
          <el-avatar :size="100" :src="userInfo.avatar">
            {{ userInfo.username ? userInfo.username[0].toUpperCase() : 'U' }}
          </el-avatar>
          <el-button type="primary" plain class="upload-btn" @click="handleAvatarUpload">
            更换头像
          </el-button>
        </div>

        <el-form 
          :model="userInfo"
          :rules="rules"
          ref="formRef"
          label-width="100px"
          class="profile-form"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="userInfo.username" />
          </el-form-item>
          
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="userInfo.email" />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="handleUpdate" :loading="loading">
              保存修改
            </el-button>
          </el-form-item>
        </el-form>

        <div class="danger-zone">
            <h4>其他操作</h4>
          <div class="danger-actions">
            <el-button type="danger" plain @click="handleResetPassword">
              重置密码
            </el-button>
            <el-button type="danger" @click="handleDeleteAccount">
              注销账号
            </el-button>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { request } from '../../api/request'

const router = useRouter()
const formRef = ref(null)
const loading = ref(false)

// 用户信息
const userInfo = reactive({
  username: '',
  email: '',
  avatar: ''
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, message: '用户名长度不能小于3个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}

// 获取用户信息
const getUserInfo = async () => {
  try {
    const storedUser = localStorage.getItem('user')
    if (storedUser) {
      const user = JSON.parse(storedUser)
      userInfo.username = user.username
      userInfo.email = user.email
      userInfo.avatar = user.avatar
    }
  } catch (error) {
    ElMessage.error('获取用户信息失败')
  }
}

// 更新用户信息
const handleUpdate = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    const data = JSON.stringify({
      id: JSON.parse(localStorage.getItem('user')).id,
      username: userInfo.username,
      password: JSON.parse(localStorage.getItem('user')).password,      
      email: userInfo.email,
      createdAt: JSON.parse(localStorage.getItem('user')).createdAt,
      updatedAt: JSON.parse(localStorage.getItem('user')).updatedAt,
      status: JSON.parse(localStorage.getItem('user')).status,
    })
    const response = await request.put('/user', data)
    
    if (response) {
      ElMessage.success('更新成功')
      // 更新本地存储的用户信息
      localStorage.setItem('user', JSON.stringify({
        ...JSON.parse(localStorage.getItem('user')),
        username: userInfo.username,
        email: userInfo.email
      }))
    } else {
      ElMessage.error(response.message || '更新失败')
    }
  } catch (error) {
    ElMessage.error(error.message || '更新失败')
  } finally {
    loading.value = false
  }
}

// 上传头像
const handleAvatarUpload = async () => {
  try {
    const input = document.createElement('input')
    input.type = 'file'
    input.accept = 'image/*'
    
    input.onchange = async (e) => {
      const file = e.target.files[0]
      if (!file) return
      
      // 验证文件大小（最大 2MB）
      if (file.size > 2 * 1024 * 1024) {
        ElMessage.error('图片大小不能超过 2MB')
        return
      }
      
      // 验证文件类型
      if (!['image/jpeg', 'image/png', 'image/gif'].includes(file.type)) {
        ElMessage.error('只支持 JPG、PNG、GIF 格式的图片')
        return
      }
      
      const formData = new FormData()
      formData.append('avatar', file)
      
      loading.value = true
      try {
        const response = await request.post('/user/avatar', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })
        
        if (response.success) {
          userInfo.avatar = response.data.avatarUrl
          // 更新本地存储的用户信息
          localStorage.setItem('user', JSON.stringify({
            ...JSON.parse(localStorage.getItem('user')),
            avatar: response.data.avatarUrl
          }))
          ElMessage.success('头像上传成功')
        } else {
          ElMessage.error(response.message || '头像上传失败')
        }
      } catch (error) {
        ElMessage.error('头像上传失败')
      } finally {
        loading.value = false
      }
    }
    
    input.click()
  } catch (error) {
    ElMessage.error('上传失败')
  }
}

// 重置密码
const handleResetPassword = async () => {
  try {
    const { value: newPassword } = await ElMessageBox.prompt('请输入新密码', '重置密码', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputType: 'password',
      inputValidator: (value) => {
        if (!value) {
          return '请输入新密码'
        }
        if (value.length < 6) {
          return '密码长度不能小于6个字符'
        }
        return true
      }
    })
    
    if (newPassword) {
      loading.value = true
      try {
        const data = JSON.stringify({
          id: JSON.parse(localStorage.getItem('user')).id,
          username: JSON.parse(localStorage.getItem('user')).username,
          password: newPassword,
          email: JSON.parse(localStorage.getItem('user')).email,
          createdAt: JSON.parse(localStorage.getItem('user')).createdAt,
          updatedAt: JSON.parse(localStorage.getItem('user')).updatedAt,
          status: JSON.parse(localStorage.getItem('user')).status,
        })
        const response = await request.put('/user', data)
        
        if (response) {
          ElMessage.success('密码重置成功，请重新登录')
          // 清除登录信息
          localStorage.removeItem('token')
          localStorage.removeItem('user')
          router.push('/login')
        } else {
          ElMessage.error('密码重置失败')
        }
      } catch (error) {
        ElMessage.error('密码重置失败')
      } finally {
        loading.value = false
      }
    }
  } catch (error) {
    // 用户取消操作
  }
}

// 注销账号
const handleDeleteAccount = async () => {
  try {
    await ElMessageBox.confirm(
      '注销账号后，所有数据将被永久删除且无法恢复，是否继续？',
      '警告',
      {
        confirmButtonText: '确定注销',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )
    
    loading.value = true
    try {
      const response = await request.delete('/user/'+JSON.parse(localStorage.getItem('user')).id)
      
      if (response) {
        ElMessage.success('账号已注销')
        // 清除登录信息
        localStorage.removeItem('token')
        localStorage.removeItem('user')
        router.push('/login')
      } else {
        ElMessage.error('注销账号失败')
      }
    } catch (error) {
      ElMessage.error('注销账号失败')
    } finally {
      loading.value = false
    }
  } catch (error) {
    // 用户取消操作
  }
}

onMounted(() => {
  getUserInfo()
})
</script>

<style scoped>
.profile-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.profile-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.card-header h2 {
  margin: 0;
  font-size: 1.5em;
  color: #333;
}

.profile-content {
  padding: 20px 0;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 30px;
}

.upload-btn {
  margin-top: 16px;
}

.profile-form {
  max-width: 500px;
  margin: 0 auto;
}

.danger-zone {
  margin-top: 40px;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

.danger-zone h4 {
  /* color: #f56c6c; */
  font-size: 1.2em;
  margin-bottom: 20px;
}

.danger-actions {
  display: flex;
  gap: 16px;
}

:deep(.el-input__wrapper) {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}
</style> 